package tech.aistar.controller.foster;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tech.aistar.entity.foster.Article;
import tech.aistar.entity.foster.CatComment;
import tech.aistar.entity.foster.Replay;
import tech.aistar.service.foster.IArticleService;
import tech.aistar.service.foster.ICatCommentService;
import tech.aistar.service.foster.IReplayService;
import tech.aistar.utill.DateUtil;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICatCommentService catCommentService;

    @Autowired
    private IReplayService replayService;

    @ResponseBody
    @GetMapping("/allArticle")
    public List<Article> getAllArticle(){
        return articleService.findAll();
    }

    @GetMapping("/allArticleView")
    public String getAllArticleView(Model model,Integer pageNum,String type){
        if (null==pageNum) pageNum = 1;
        if (null == type) type = "";
        Page<Article> articlePage=articleService.findByType(type,pageNum-1,5);
        model.addAttribute("type2",type);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("articles",articlePage.getContent());
        model.addAttribute("pageNumber",articlePage.getTotalElements());
        return "foster/allArticle";
    }

    @ResponseBody
    @PostMapping("/addArticle")
    public void addArticle(@RequestBody Article article){
        article.setCreateDate(DateUtil.dateFormat(new Date()));
        articleService.add(article);
    }

    @GetMapping("/articleView")
    public String articleView(Model model,String id) {
        //通过article的id获取文章
        Article article = articleService.findById(id);
        articleService.addView(article);
        //通过文章id获取该文章的评论
        List<CatComment> comments = catCommentService.findByOwnerId(id);
        for (CatComment comment : comments) {
            System.out.println(comment);
        }

        model.addAttribute("comments", comments);
        model.addAttribute("article", article);
        return "foster/article";
    }

    @RequestMapping("/replayView")
    public String replayView(String id){

        Replay replay =replayService.findById(id);

        CatComment catComment = catCommentService.findById(replay.getCommentId());

        Article article = articleService.findById(catComment.getOwnerId());

        return "redirect:articleView?id="+article.getId();
    }

}
